public class NumSquares {
    // leetcode 完全平方数
    // https://leetcode.cn/problems/perfect-squares/description/?envType=study-plan-v2&envId=top-100-liked
    public int numSquares(int n) {
        // 可以转换为完全背包问题
        int aim = (int)Math.sqrt(n);
        int[][] dp = new int[aim+1][n+1];
        int INF = 0x3f3f3f3f;
        for (int j = 1; j < n+1; j++) dp[0][j] = INF;
        for (int i = 1; i < aim + 1; i++) {
            for (int j = 0; j < n + 1; j++) {
                dp[i][j] = dp[i-1][j];
                if (j >= i*i) {
                    dp[i][j] = Math.min(dp[i][j], dp[i][j-i*i] + 1);
                }
            }
        }
        return dp[aim][n];
    }

    // 空间优化
    public int numSquares1(int n) {
        // 可以转换为完全背包问题
        int aim = (int)Math.sqrt(n);
        int[] dp = new int[n+1];
        int INF = 0x3f3f3f3f;
        for (int j = 1; j < n+1; j++) dp[j] = INF;
        for (int i = 1; i < aim + 1; i++) {
            for (int j = i*i; j < n + 1; j++) {
                dp[j] = Math.min(dp[j], dp[j-i*i] + 1);
            }
        }
        return dp[n];
    }
}
